//
//  Record.m
//  IconPair
//
//  Created by Yangss on 2010-6-26.
//  Copyright 2010 LotusVille. All rights reserved.


#import "Record.h"

@implementation Record
@synthesize name;
@synthesize score;
@synthesize level;

-(void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:self.name forKey:kRecordName];
    [encoder encodeInt:self.score forKey:kRecordScore];
}
-(id)initWithCoder:(NSCoder *)decoder
{
    self = [super init];
    if ( self != nil )
    {
        self.name = [decoder decodeObjectForKey:kRecordName];
        self.score = [decoder decodeIntForKey:kRecordScore];
    }
    return self;
}


+(int) trySaveScoreRecord: (Record *) newRecord{
	NSArray *scores = [Record getHighScores];
	int scoreIndex = 0;
	for (int i=0; i<[scores count]; scoreIndex++, i++) {
		Record *each = [scores objectAtIndex:i];
		if (each.score<= newRecord.score) {
			scoreIndex = i;
			break;
		}		
	}
	if (scoreIndex < 0 || scoreIndex >= kMaxRecordCount) {
		return -1;
	}

	NSMutableArray *newScores = [NSMutableArray arrayWithArray: scores];
	[newScores insertObject:newRecord atIndex:scoreIndex];
	if ([newScores count] > kMaxRecordCount) {
		[newScores removeLastObject];
	}

	NSData *data = [NSKeyedArchiver archivedDataWithRootObject:newScores];
	[[NSUserDefaults standardUserDefaults] setValue:data forKey:kRecordScore];
	[[NSUserDefaults standardUserDefaults] synchronize];	
	return scoreIndex;
}

+(void) tryClearScoreRecord
{
	NSArray *scores = [Record getHighScores];
	NSMutableArray *newScores = [NSMutableArray arrayWithArray: scores];
	[newScores removeAllObjects];
	
	NSData *data = [NSKeyedArchiver archivedDataWithRootObject:newScores];
	[[NSUserDefaults standardUserDefaults] setValue:data forKey:kRecordScore];
	[[NSUserDefaults standardUserDefaults] synchronize];	
}


+(NSArray *) getHighScores{
	NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kRecordScore];
	return [NSKeyedUnarchiver unarchiveObjectWithData: data];
}


+(Record *)createCurrentRecord{
	Record *newRecord = [[Record alloc] init];
	newRecord.name = [User name];
	newRecord.score = [User score];
	newRecord.level = [User winedLevel];
	return newRecord;
}

@end
